package com.ruyuan.commodity.common.mamager.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruyuan.commodity.model.goodssearch.SearchKeywordDO;
import com.ruyuan.commodity.open.api.model.common.WebPage;
import com.ruyuan.commodity.common.mamager.SearchKeywordManager;
import com.ruyuan.commodity.common.mapper.SearchKeywordMapper;
import com.ruyuan.commodity.exception.ServiceException;
import com.ruyuan.commodity.open.api.model.errorcode.GoodsErrorCode;
import com.ruyuan.commodity.open.api.model.util.DateUtil;
import com.ruyuan.commodity.utils.PageConvert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 搜索关键词业务实现类
 */
@Service
public class SearchKeywordManagerImpl implements SearchKeywordManager {

    @Autowired
    private SearchKeywordMapper searchKeywordMapper;

    /**
     * 添加搜索关键字
     * @param keyword 关键字
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(String keyword) {
        if (StringUtils.isEmpty(keyword)) {
            throw new ServiceException(GoodsErrorCode.E310.code(), "关键字不能为空！");
        }
        SearchKeywordDO searchKeywordDO = new SearchKeywordDO(keyword);
        this.searchKeywordMapper.insert(searchKeywordDO);
    }

    /**
     * 关键字历史列表
     * @param pageNo 每页
     * @param pageSize 每页数量
     * @param keyword 关键字
     * @return
     */
    @Override
    public WebPage list(Long pageNo, Long pageSize, String keyword) {
        QueryWrapper<SearchKeywordDO> searchKeywordQueryWrapper = new QueryWrapper<SearchKeywordDO>()
                .gt("count", 0)
                //如果关键字不为空，则模糊查询keyword
                .like(!StringUtils.isEmpty(keyword), "keyword", keyword)
                .orderByDesc("count", "id");

        IPage iPage = this.searchKeywordMapper.selectPage(new Page<>(pageNo,pageSize), searchKeywordQueryWrapper);
        return PageConvert.convert(iPage);
    }
    /**
     * 更新关键字数据
     * @param keyword 关键字
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(String keyword) {
        if (StringUtils.isEmpty(keyword)) {
            return;
        }
        this.searchKeywordMapper.updateKeywordCount(DateUtil.getDateline(),keyword);
    }

    /**
     * 查询关键词是否存在
     * @param keyword 关键字
     * @return 是否存在
     */
    @Override
    public boolean isExist(String keyword) {
        int count = this.searchKeywordMapper.selectCount(new QueryWrapper<SearchKeywordDO>()
                .eq("keyword",keyword));
        return count > 0;
    }
}
